//
//  SearchViewController.m
//  ChunLaiZhuangClient
//
//  Created by zzs on 16/3/10.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "SearchViewController.h"
#import "HotSearchFrameModel.h"
#import "CustomHotTagTableViewCell.h"
#import "SKTagView/SKTagView.h"
#import "CustomClearBtTableViewCell.h"
#import "SKTagView/SKTagView.h"
#import "SearchResultWithProductViewController.h"
#import "QLKDataBaseManager.h"
#import "SearchHistoryModel.h"
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSArray *searchArray;
    CustomHotTagTableViewCell *hotcell;
    UITextField *searchTF;
    SearchHotWordModel *hotModel;
}
@property (copy, nonatomic, nullable) void (^didTapTagAtIndex)(NSUInteger index);
@end

@implementation SearchViewController
static NSString *const kTagsTableCellReuseIdentifier = @"TagsTableCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    //模拟数据
    [self setNaviLeftButton:@""];
    [self.view addSubview:self.searchBarView];
    [searchTF becomeFirstResponder];
    [self getHotSearchKeyword];
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadHistoryData];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
#pragma mark-从本地获取搜索历史
-(void)loadHistoryData{
    searchArray=[[QLKDataBaseManager shareDataBaseManager] queyAllDrugHistoryContents];
    [self.displayView reloadData];
}
#pragma mark-获取热门搜索词
-(void)getHotSearchKeyword{
     [[LKDHud shareHud] showLoadingView];
   [ApiClient getSearchHotWordDidFinishLoaded:^(SearchHotWordModel *model, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
       hotModel=model;
       [self.view addSubview:self.displayView];
       
   } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
   }];
}
- (void)configureCell: (CustomHotTagTableViewCell *)cell atIndexPath: (NSIndexPath *)indexPath {
    cell.tagView.preferredMaxLayoutWidth = SCREEN_WIDTH;
    cell.tagView.padding = UIEdgeInsetsMake(12, 12, 12, 12);
    cell.tagView.interitemSpacing = 15;
    cell.tagView.lineSpacing = 10;
    
    [cell.tagView removeAllTags];
    
    //Add Tags
    [hotModel.data.keywords enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SKTag *tag = [SKTag tagWithText:obj];
        tag.textColor = [UIColor blackColor];
        tag.fontSize = 15;
        tag.padding = UIEdgeInsetsMake(5, 12.5, 5, 12.5);
        tag.cornerRadius = 15;
        tag.borderColor=[UIColor colorWithHexString:@"a0a0a0"];
        tag.borderWidth=0.5;

        
        [cell.tagView addTag:tag];
    }];
    
    cell.tagView.didTapTagAtIndex = ^(NSUInteger index) {
            SearchResultWithProductViewController *searcVC=[[SearchResultWithProductViewController alloc] init];
            searcVC.placeHoldStr=hotModel.data.keywords[index];
            [self.navigationController pushViewController:searcVC animated:YES];
    };

}
-(void)cancleAction:(UIButton*)bt{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UIView*)searchBarView{
    if (!_searchBarView) {
        _searchBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 128/2)];
        _searchBarView.backgroundColor=[UIColor colorWithHexString:@"fafafa"];
        UIButton *searchBt=[UIButton buttonWithType:UIButtonTypeCustom];
        searchBt.frame=CGRectMake(10, 25, SCREEN_WIDTH-10-65, 34);
        searchBt.layer.cornerRadius=18;
        searchBt.clipsToBounds=YES;
        searchBt.layer.borderColor=[UIColor colorWithHexString:@"d8d8f8"].CGColor;
        searchBt.layer.borderWidth=0.5;
        searchBt.backgroundColor=[UIColor whiteColor];
        UIImageView *searchIcon=[[UIImageView alloc] initWithFrame:CGRectMake(20, 9, 16, 16)];
        searchIcon.image=[UIImage imageNamed:@"icon_search"];
        
        [searchBt addSubview:searchIcon];
        searchTF=[[UITextField alloc] initWithFrame:CGRectMake(0,5,searchBt.width-40, 25)];
        searchTF.clearButtonMode=UITextFieldViewModeAlways;
        searchTF.borderStyle=UITextBorderStyleNone;
        searchTF.placeholder=@"输入想要搜索的商品名称";
        searchTF.font=[UIFont systemFontOfSize:12];
        searchTF.returnKeyType=UIReturnKeySearch;
        searchTF.enablesReturnKeyAutomatically = YES;
        searchTF.left=searchIcon.right+7;
        searchTF.delegate=self;
        [searchBt addSubview:searchTF];
        [_searchBarView addSubview:searchBt];
        UIButton *cancelBt=[UIButton buttonWithType:UIButtonTypeCustom];
        cancelBt.frame=CGRectMake(searchBt.right,25, 64, 35);
        [cancelBt setTitle:@"取消" forState:UIControlStateNormal];
        cancelBt.titleLabel.font=[UIFont systemFontOfSize:15];
        [cancelBt setTitleColor:[UIColor colorWithHexString:@"000000"] forState:UIControlStateNormal];
        [cancelBt addTarget:self action:@selector(cancleAction:) forControlEvents:UIControlEventTouchUpInside];
        [_searchBarView addSubview:cancelBt];
    }
    return _searchBarView;
}
-(UITableView*)displayView{
    if (!_displayView) {
        _displayView=[[UITableView alloc] initWithFrame:CGRectMake(0,self.searchBarView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        _displayView.delegate=self;
        _displayView.dataSource=self;
        _displayView.backgroundColor=[UIColor clearColor];
        _displayView.tableFooterView=[[UIView alloc] initWithFrame:CGRectZero];
        UIScrollView *scrollow=(UIScrollView*)_displayView;
        scrollow.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag;
        // [_displayView setSeparatorColor:[UIColor redColor]];
    }
    return _displayView;
}
#pragma mark-UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            if (searchArray.count>0) {
               return searchArray.count+1;
            }else{
                return 0;
            }
            
            break;
        default:
            return 0;
            break;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            
            
            hotcell = [tableView dequeueReusableCellWithIdentifier:
                                               kTagsTableCellReuseIdentifier ];
            if (hotcell == nil) {
                hotcell = [[[NSBundle mainBundle] loadNibNamed:@"CustomHotTagTableViewCell"  owner:self options:nil] lastObject];
                
            }
      
            [self configureCell: hotcell atIndexPath:indexPath];
            hotcell.selectionStyle=UITableViewCellSelectionStyleNone;
            self.didTapTagAtIndex=hotcell.tagView.didTapTagAtIndex;
            return hotcell;

        }
            break;
        case 1:
        {
            if (indexPath.row==searchArray.count) {
                static NSString *identifier = @"CustomClearBtTableViewCell";
                CustomClearBtTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:
                                                      identifier];
                if (cell == nil) {
                    cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomClearBtTableViewCell"  owner:self options:nil] lastObject];
                    
                }
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;

            }else{
                static NSString *identifier = @"cell";
                UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:
                                         identifier];
                if (cell == nil) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                    
                }
                SearchHistoryModel *historyModel=searchArray[indexPath.row];
                cell.textLabel.text=historyModel.content;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;
 
            }
           

        }
            break;
        default:
            return nil;
            break;
    }
    
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            return [hotcell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 1;
            
        }
            break;
            
        default:
            if (indexPath.row==searchArray.count) {
                return 60;
            }else{
               return 44;
            }
            break;
    }
   
   
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *aview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,25)];
    aview.backgroundColor=[UIColor colorWithHexString:@"efeff4"];
    UILabel *titleLable=[[UILabel alloc] initWithFrame:CGRectMake(15, 2,100, 20)];
    titleLable.textAlignment=NSTextAlignmentLeft;
    titleLable.font=[UIFont systemFontOfSize:12];
    titleLable.textColor=[UIColor colorWithHexString:@"a3a3a4"];
    [aview addSubview:titleLable];
    switch (section) {
        case 0:
           titleLable.text=@"热门搜索";
            break;
        case 1:
            if (searchArray.count>0){
               titleLable.text=@"搜索历史";
            }else{
               titleLable.text=@"";
            }
          
            break;
        default:
            break;
    }
        return aview;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return;
    }
    SearchHistoryModel *historyModel=searchArray[indexPath.row];
    SearchResultWithProductViewController *searcVC=[[SearchResultWithProductViewController alloc] init];
    searcVC.placeHoldStr=historyModel.content;
    [self.navigationController pushViewController:searcVC animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *str = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (str.length>0) {
        [[QLKDataBaseManager shareDataBaseManager] insertHistoryContentToDB:textField.text];
    }
    SearchResultWithProductViewController *searcVC=[[SearchResultWithProductViewController alloc] init];
    searcVC.placeHoldStr=textField.text;
    [self.navigationController pushViewController:searcVC animated:YES];

    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
